package com.ruoyi.web.controller.walmart;

import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.WalmartConstant;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.walmart.State;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.depot.domain.WalmartStockProductDetails;
import com.ruoyi.depot.service.IWalmartStockPlanService;
import com.ruoyi.walmart.domain.Inventory.FulfillmentInventory;
import com.ruoyi.walmart.domain.Inventory.Inventory;
import com.ruoyi.walmart.domain.Inventory.InventoryPayload;
import com.ruoyi.walmart.domain.InventoryLog.FulfillmentInventoryLog;
import com.ruoyi.walmart.domain.InventoryLog.InventoryLogSearch;
import com.ruoyi.walmart.domain.InventoryLog.InventoryLogPayload;
import com.ruoyi.walmart.domain.Items.*;
import com.ruoyi.walmart.domain.ProductParameters;
import com.ruoyi.walmart.domain.QuerySummary;
import com.ruoyi.walmart.domain.address.Address;
import com.ruoyi.walmart.domain.auth.ShopAuth;
import com.ruoyi.walmart.domain.order.*;
import com.ruoyi.walmart.domain.order.vo.DailySales;
import com.ruoyi.walmart.domain.shipments.*;
import com.ruoyi.walmart.domain.shipments.dto.ShipmentStockFilters;
import com.ruoyi.walmart.dto.ShipmentItemDTO;
import com.ruoyi.walmart.http.WalmartRequest;
import com.ruoyi.walmart.mapper.Inventory.FulfillmentInventoryLogMapper;
import com.ruoyi.walmart.mapper.order.OrderMapper;
import com.ruoyi.walmart.mapper.shipments.ShipmentInboundMapper;
import com.ruoyi.walmart.mapper.shipments.ShipmentLabelMapper;
import com.ruoyi.walmart.mapper.shipments.ShipmentMapper;
import com.ruoyi.walmart.mapper.shipments.ShipmentStockMapper;
import com.ruoyi.walmart.service.Inventory.FulfillmentInventoryLogService;
import com.ruoyi.walmart.service.Inventory.FulfillmentInventoryService;
import com.ruoyi.walmart.service.address.AddressService;
import com.ruoyi.walmart.service.address.StateService;
import com.ruoyi.walmart.service.auth.ShopAuthService;
import com.ruoyi.walmart.service.items.ItemsService;
import com.ruoyi.walmart.service.items.PairProductsService;
import com.ruoyi.walmart.service.items.ReportItemService;
import com.ruoyi.walmart.service.order.*;
import com.ruoyi.walmart.service.shipments.*;
import com.ruoyi.walmart.thread.OrderProcessingTask;
import com.ruoyi.walmart.thread.OrderStatusProcessingTask;
import com.ruoyi.walmart.util.walmartUtil;
import lombok.extern.log4j.Log4j2;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Log4j2
@RestController
@RequestMapping("/walmart")
@Component("ItemsDate")
public class WalmartController extends BaseController {

    @Autowired
    ItemsService itemsService;
    @Autowired
    ShopAuthService shopAuthService;
    @Autowired
    PairProductsService pairProductsService;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    OrderChargeService orderChargeService;
    @Autowired
    InstantSalesService instantSalesService;
    @Autowired
    FulfillmentInventoryService fulfillmentInventoryService;
    @Autowired
    ShipmentService shipmentService;
    @Autowired
    ShipmentItemService shipmentItemService;
    @Autowired
    ReportItemService reportItemService;
    @Autowired
    AddressService addressService;
    @Autowired
    StateService stateService;
    @Autowired
    RedisCache redisCache;
    @Autowired
    RealTimeSalesService realTimeSalesService;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    FulfillmentInventoryLogService fulfillmentInventoryLogService;
    @Autowired
    FulfillmentInventoryLogMapper fulfillmentInventoryLogMapper;
    @Autowired
    ShipmentLabelService shipmentLabelService;
    @Autowired
    ShipmentLabelMapper shipmentLabelMapper;
    @Autowired
    IWalmartStockPlanService iWalmartStockPlanService;
    @Autowired
    ShipmentMapper shipmentMapper;
    @Autowired
    ShipmentInboundMapper shipmentInboundMapper;
    @Autowired
    ShipmentInboundService shipmentInboundService;
    @Autowired
    ShipmentStockService shipmentStockService;
    @Autowired
    ShipmentStockMapper shipmentStockMapper;

    @GetMapping("/aa")
    public AjaxResult getInt(){
        ShopAuth shopAuth = new ShopAuth();
        shopAuth.setAuthId(1L);
        List<ShopAuth> shopAuthList = shopAuthService.selectAllList(shopAuth);
        for (ShopAuth newShopAuth:shopAuthList) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("sku","CC0790-04");
            String url = "https://marketplace.walmartapis.com/v3/inventories/CC0790-04";
            String request = WalmartRequest.request(url, Method.GET, null, newShopAuth);
            return success(request);
        }
        return null;

    }

    @GetMapping("/qwe")
    public AjaxResult getSearch1(){
        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);
        for (ShopAuth shopAuth : selectAllList) {
            Map<String, Object> paramMap = new HashMap<>();
            //paramMap.put("sku","PE0013");
            String url = WalmartConstant.BASE_URL+WalmartConstant.GET_PRODUCTS_US_URL+WalmartConstant.GET_SEARCH_US_URL;
            url = "https://marketplace.walmartapis.com/v3/items/PE0013";
            String request = WalmartRequest.request(url, Method.GET, paramMap, shopAuth);
            ProductItem productItem = JSON.parseObject(request, ProductItem.class);
            return success(productItem);
        }
        return null;
    }

    /**
     * 展示到页面上出货量数据
     * @param shipment
     * @return
     */
    @PreAuthorize("@ss.hasPermi('walmart:shipment:list')")
    @GetMapping("/WFL/shipmentList")
    public TableDataInfo shipmentList(Shipment shipment){
        startPage();
        List<Shipment> shipmentList = shipmentService.selectList(shipment);
        return getDataTable(shipmentList);
    }

    /**
     * 查询不同出货量状态的数量
     * @param shipment
     * @return
     */
    @GetMapping("/WFL/shipmentCountStatus")
    public AjaxResult shipmentCountStatus(Shipment shipment){
        return success(shipmentService.countByStatus(shipment));
    }


    @GetMapping("/WFL/orderFulfillment")
    public AjaxResult orderFulfillment(){
        ShopAuth shopAuth = new ShopAuth();
        shopAuth.setAuthId(1L);
        List<ShopAuth> shopAuthList = shopAuthService.selectAllList(shopAuth);
        for (ShopAuth newShopAuth:shopAuthList) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("shipmentId","0329295GDM");
            String url = "https://marketplace.walmartapis.com/v3/settings/shipping/templates";
            String request = WalmartRequest.request(url, Method.GET, null, newShopAuth);
            return success(request);
        }
        return null;
    }


    /**
     * 查询出库量产品
      * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('walmart:shipment:detail')")
    @GetMapping("/WFL/shipmentItems")
    public AjaxResult shipmentItems(ShipmentItem shipmentItem){
        return success(shipmentItemService.selectAllList(shipmentItem));
    }

    /**
     * 查询所有商品
     * @param items
     * @return
     */
    @PreAuthorize("@ss.hasPermi('commodity:relatedProducts:query')")
    @GetMapping("/items/list")
    public TableDataInfo getList(VoItems items){
        startPage();
        List<Items> itemsList = itemsService.selectItemsPair(items);
        return getDataTable(itemsList);
    }

    /**
     * 添加配对商品
     * @param pairProducts
     * @return
     */
    @PreAuthorize("@ss.hasPermi('commodity:relatedProducts:pairing')")
    @PostMapping("/items/addPair")
    public AjaxResult getInsertAll(@RequestBody PairProducts pairProducts){
        pairProducts.setHead(getNickname());
        pairProducts.setSaleResponsibleTime(DateUtils.getNowDate());
        return toAjax(pairProductsService.insertAll(pairProducts));
    }

    /**
     * 分配产品负责人
     * @param pairIds
     * @param head
     * @return
     */
//    @PreAuthorize("@ss.hasPermi('commodity:relatedProducts:addProductUser')")
//    @PutMapping("/items/updateProductPair/{pairIds}/{head}")
//    public AjaxResult getUpdateProductPair(@PathVariable Long[] pairIds,@PathVariable String head){
//        return toAjax(pairProductsService.updateProductPairIdInt(pairIds,head));
//    }

    /**
     * 分配销售负责人
     * @param pairIds
     * @param head
     * @return
     */
    @PreAuthorize("@ss.hasPermi('commodity:relatedProducts:addSaleUser')")
    @PutMapping("/items/updateSalePair/{pairIds}/{head}")
    public AjaxResult getUpdateSalePair(@PathVariable Long[] pairIds,@PathVariable String head){
        return toAjax(pairProductsService.updateSalePairIdInt(pairIds,head));
    }





    @GetMapping("/items/selectPair/{pairIds}")
    public AjaxResult getSelectPair(@PathVariable Long[] pairIds){
        return success(pairProductsService.selectByPairId(pairIds));
    }

    /**
     * 修改产品
     * @param pairId
     * @param productId
     * @return
     */
    @PutMapping("/items/updateProductId/{pairId}/{productId}")
    public AjaxResult getUpdateProductId(@PathVariable Long pairId,@PathVariable Long productId){
        return toAjax(pairProductsService.updateProductIdInt(pairId,productId));
    }

    /**
     * 解绑产品配对
     * @param pairId
     * @return
     */
    @PutMapping("/items/updatePairProduct/{pairId}")
    public AjaxResult getUpdatePairProduct(@PathVariable Long pairId){
        return toAjax(pairProductsService.updatePairId(pairId,getNickname()));
    }

    /**
     * 解绑负责人
     * @param pairId
     * @return
     */
    @PutMapping("/items/updateHead/{pairId}")
    public AjaxResult getUpdateHead(@PathVariable Long pairId){
        String nickname = getNickname();
        return toAjax(pairProductsService.updateHead(pairId,nickname));
    }

    /**
     * 报告请求状态
     * @return
     */
    @GetMapping("/reportRequests")
    public AjaxResult getReportRequest(){
        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);
        for (ShopAuth shopAuth : selectAllList) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("requestId","");
            String url = "https://marketplace.walmartapis.com/v3/reports/reportRequests/d8dc2da4-4416-4b2f-be88-d926548aac51";
            String json = WalmartRequest.request(url, Method.GET, paramMap,shopAuth);
            return success(json);
        }
        return null;
    }

    /**
     * 订单列表查询
     * @return
     */
    @PreAuthorize("@ss.hasPermi('walmart:order:list')")
    @GetMapping("/order/list")
    public TableDataInfo getOrderList(VoOrder order){
        startPage();
        List<AllOrder> allOrders = orderService.selectOrderAuthId(order);
        allOrders.stream().forEach(allOrder -> {
            List<OrderItem> orderItemList = orderItemService.selectAllByCustomerOrderId(
                    allOrder.getCustomerOrderId(),
                    allOrder.getAuthId(),
                    allOrder.getPurchaseOrderId()
            );
            allOrder.setOrderItemList(orderItemList);
        });
        return getDataTable(allOrders);
    }

    @PreAuthorize("@ss.hasPermi('walmart:orderInstant:list')")
    @GetMapping("/order/instant")
    public TableDataInfo getInstant(InstantSales instantSales){
        startPage();
        // 获取基础信息和汇总数据
        List<InstantSales> instantSalesList = instantSalesService.selectAllBase(instantSales);
        List<InstantSales> selectQty = instantSalesService.selectQty(instantSales);

        // 获取每日销售数据
        List<DailySales> dailySalesList = instantSalesService.selectDailySales(instantSales);

        // 将每日销售数据按SKU分组
        Map<String, List<DailySales>> dailySalesMap = dailySalesList.stream()
                .collect(Collectors.groupingBy(DailySales::getSellerSku));

        // 遍历 instantSalesList
        for (InstantSales sales : instantSalesList) {
            String sku = sales.getSellerSku();

            // 在 selectQty 中查找匹配的 SKU
            for (InstantSales selectQtyItem : selectQty) {
                if (sku.equals(selectQtyItem.getSellerSku())) {
                    // 如果找到匹配的 SKU，则赋值数量
                    sales.setQty(selectQtyItem.getQty());
                    sales.setQty3days(selectQtyItem.getQty3days());
                    sales.setQty7days(selectQtyItem.getQty7days());
                    sales.setQty15days(selectQtyItem.getQty15days());
                    sales.setQty30days(selectQtyItem.getQty30days());
                    sales.setQty60days(selectQtyItem.getQty60days());
                    sales.setQty90days(selectQtyItem.getQty90days());
                    break; // 找到匹配的 SKU 后退出内部循环
                }
            }

            // 合并每日销售数据
            List<DailySales> skuDailySales = dailySalesMap.getOrDefault(sku, Collections.emptyList());
            sales.setDailySalesList(skuDailySales);
        }
        return getDataTable(instantSalesList);
    }

    @GetMapping("/rules")
    public AjaxResult getRules(String url){
        ShopAuth shopAuth = new ShopAuth();
        shopAuth.setAuthId(1L);
        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);
        for (ShopAuth newShopAuth : selectAllList) {
            String request = WalmartRequest.request(url, Method.GET, null, newShopAuth);
            return success(request);
        }
        return null;
    }


    /**
     * 递归查询州
     * @param state
     * @return
     */
    @GetMapping("/shipment/stateTree")
    public AjaxResult getStateTree(State state){
        return success(stateService.selectStateTreeList(state));
    }

    /**
     * 查询地址
     * @param address
     * @return
     */
    @GetMapping("/shipment/selectAddress")
    public AjaxResult getSelectAddress(Address address){
        return success(addressService.selectAll(address));
    }

    /**
     * 条件查询实时销量
     * @param realTimeSales
     * @return
     */
    @GetMapping("/real/sales")
    public AjaxResult getSelectRealTimeSalesList(RealTimeSales realTimeSales){
        return success(realTimeSalesService.selectList(realTimeSales));
    }


    /**
     * walmart汇总订单列表
     * @return
     */
    @GetMapping("/order/getOrderSummary")
    public QuerySummary getOrderSummary(QuerySummary orderSummary){
        return orderItemService.getOrderSummary(orderSummary);
    }

    /**
     * walmart汇总链接列表
     * @return
     */
    @GetMapping("/items/getItemsSummar")
    public QuerySummary getItemsSummar(QuerySummary itemsSummary){
        return itemsService.getItemsSummary(itemsSummary);
    }

    /**
     * walmart同步订单任务（15分钟同步一次）
     * @return
     */
    @GetMapping("/order/ordersTask")
    public AjaxResult ordersTask() {
        ExecutorService executor = Executors.newFixedThreadPool(Math.min(Runtime.getRuntime().availableProcessors(), 10));

        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);

        // **链式执行，每个店铺一个一个执行**
        CompletableFuture<Void> chain = CompletableFuture.completedFuture(null);

        for (ShopAuth shopAuth : selectAllList) {
            chain = chain.thenCompose(ignore -> processShopAuth(shopAuth, executor));
        }

        // **等待所有店铺执行完成**
        chain.join();
        executor.shutdown();

        return success();
    }
    /**
     * **单个店铺的执行逻辑（独立事务）**
     */
    private CompletableFuture<Void> processShopAuth(ShopAuth shopAuth, Executor executor) {
        return CompletableFuture.runAsync(() -> {
            List<AllOrder> orderList = new ArrayList<>();
            List<OrderItem> orderItemList = new ArrayList<>();
            List<OrderCharge> orderChargeList = new ArrayList<>();
            List<String> orderIdsToDelete = new ArrayList<>();

            try {
                Integer result = orderMapper.checkExistence(shopAuth.getAuthId());
                OrderProcessingTask task = null;

                Date date = null;
                if (result != null) {
                    date = orderService.delayOrderDate(shopAuth.getAuthId());
                    if (date != null) {
                        orderIdsToDelete = orderService.customerOrderId(shopAuth.getAuthId());
                    }
                }

                task = new OrderProcessingTask(shopAuth, orderList, orderItemList, orderChargeList, date);

                if (task != null) {
                    log.info("开始同步 Walmart 订单，ShopAuth: {}", shopAuth.getAuthId());
                    task.run();
                    log.info("完成同步 Walmart 订单，ShopAuth: {}", shopAuth.getAuthId());
                }

                // **在事务管理下执行删除 & 保存**
                orderService.deleteAndSaveData(shopAuth.getAuthId(),orderIdsToDelete, orderItemList, orderChargeList, orderList);

            } catch (Exception e) {
                log.error("订单同步失败，ShopAuth: {}", shopAuth.getAuthId(), e);
                // **失败后不影响其他店铺**
            }
        }, executor);
    }
    /**
     * walmart同步订单状态任务（1天同步一次）
     * @return
     */
    @GetMapping("/order/ordersStatusTask")
    public AjaxResult ordersStatusTask(){
        ExecutorService executor = Executors.newFixedThreadPool(2);// 定义线程池大小
        List<OrderItem> orderItemList = new ArrayList<>();
        List<Callable<Void>> tasks = new ArrayList<>();
        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);
        for (ShopAuth shopAuth : selectAllList) {
            tasks.add(() -> {
                /** 查询是否已有定时任务*/
                Integer result  = orderMapper.checkExistence(shopAuth.getAuthId());
                OrderStatusProcessingTask task = null;
                if(result == null){
                    task = new OrderStatusProcessingTask(shopAuth, orderItemList,null);
                }else{
                    /** 查询最近更新的订单时间，往前一个月数据*/
                    Date date = orderService.orderDate(shopAuth.getAuthId());
                    if(date != null){
                        task = new OrderStatusProcessingTask(shopAuth,orderItemList,date);
                    }

                }
                task.run();
                return null;
            });
        }
        try {
            executor.invokeAll(tasks);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        executor.shutdown();
        // 更新订单明细状态
        return success(orderItemService.updateOrderStatusBatch(orderItemList));
    }

    /**
     * walmart链接获取
     * @return
     */
    @GetMapping("/order/itemsTask")
    public AjaxResult itemsTask(){

        ExecutorService executor = Executors.newFixedThreadPool(Math.min(Runtime.getRuntime().availableProcessors(), 10));

        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);

        // **链式执行，每个店铺一个一个执行**
        CompletableFuture<Void> chain = CompletableFuture.completedFuture(null);

        for (ShopAuth shopAuth : selectAllList) {
            chain = chain.thenCompose(ignore -> processItemsShopAuth(shopAuth, executor));
        }

        // **等待所有店铺执行完成**
        chain.join();
        executor.shutdown();

        return success();
    }
    /**
     * **单个店铺的执行逻辑（独立事务）**
     */
    private CompletableFuture<Void> processItemsShopAuth(ShopAuth shopAuth, Executor executor) {

        return CompletableFuture.runAsync(() -> {
            // 在这里你可以使用获取到的值进行其他操作
            ProductParameters productParameters = new ProductParameters();

            Long authId = shopAuth.getAuthId();

            List<Items> existingItems = itemsService.selectItemsByAuthId(authId);
            Map<String, Items> itemCacheMap = existingItems.stream()
                    .filter(item -> item.getSku() != null)
                    .collect(Collectors.toMap(Items::getSku, Function.identity(), (a, b) -> a));

            List<Items> itemsList = new ArrayList<>();
            Items items = null;
            productParameters.setLimit("50");
            String nextCursor = "*";
            while (nextCursor != null){
                productParameters.setNextCursor(nextCursor);
                JSONObject jsonObject = walmartUtil.listItemsUs(productParameters,shopAuth);
                if(jsonObject == null){
                    break;
                }
                if(jsonObject.getInteger("totalItems") != 0){
                    JSONArray array = jsonObject.getJSONArray( "ItemResponse");
                    for (Object o:array){
                        String uuid = IdUtils.fastSimpleUUID();
                        items = new Items();
                        JSONObject orderLines=(JSONObject) o;
                        items.setItemsId(uuid);
                        items.setMart(orderLines.getString("mart"));
                        items.setSku(orderLines.getString("sku"));
                        items.setWpid(orderLines.getString("wpid"));
                        items.setUpc(orderLines.getString("upc"));
                        items.setGtin(orderLines.getString("gtin"));
                        items.setProductName(orderLines.getString("productName"));
                        items.setShelf(orderLines.getString("shelf"));
                        items.setProductType(orderLines.getString("productType"));
                        items.setAmount(orderLines.getJSONObject("price").getBigDecimal("amount"));
                        items.setCurrency(orderLines.getJSONObject("price").getString("currency"));
                        items.setPublishedStatus(orderLines.getString("publishedStatus"));
                        items.setLifecycleStatus(orderLines.getString("lifecycleStatus"));
                        items.setAuthId(shopAuth.getAuthId());

                        // 检查缓存中是否有 itemId 和 imageUrl
                        Items cachedItem = itemCacheMap.get(items.getSku());
                        if (cachedItem != null &&
                                cachedItem.getImageUrl() != null && !cachedItem.getImageUrl().isEmpty()) {
                            // 直接使用缓存中的 itemId 和 imageUrl
                            items.setItemId(cachedItem.getItemId());
                            items.setImageUrl(cachedItem.getImageUrl());
                            // 可选：如果定时任务也更新 customerRating 和 numReviews，这里也复制
                            items.setCustomerRating(cachedItem.getCustomerRating());
                            items.setNumReviews(cachedItem.getNumReviews());
                        } else {
                            if(orderLines.getString("lifecycleStatus").equals("ACTIVE")){
                                // 调用 getSearch 获取 itemId 和 imageUrl
                                ProductItem search = getSearch(items, shopAuth);
                                if (search != null) {
                                    List<ProductItem.Item> searchItems = search.getItems();
                                    if (searchItems != null) {
                                        Items finalItems = items;
                                        searchItems.forEach(item -> {
                                            finalItems.setItemId(item.getItemId());
                                            finalItems.setCustomerRating(item.getCustomerRating());
                                            finalItems.setNumReviews(item.getProperties().getNum_reviews());
                                            List<ProductItem.Image> images = item.getImages();
                                            if (images != null) {
                                                images.forEach(image -> finalItems.setImageUrl(image.getUrl()));
                                            } else if (cachedItem != null && cachedItem.getImageUrl() != null) {
                                                finalItems.setImageUrl(cachedItem.getImageUrl());
                                            }
                                        });
                                    }
                                } else if (cachedItem != null && cachedItem.getImageUrl() != null) {
                                    items.setImageUrl(cachedItem.getImageUrl());
                                }
                            }
                        }
                        itemsList.add(items);
                    }
                }
                nextCursor = jsonObject.getString("nextCursor");
            }
//            if(existingItems.isEmpty()){
//                itemsService.itemsInsertList(itemsList);
//            }else{
//                itemsService.deleteItemsByAuthId(authId);
//                itemsService.itemsInsertList(itemsList);
//            }
            // 增量更新逻辑
            Map<String, Items> newItemsMap = itemsList.stream()
                    .filter(item -> item.getSku() != null)
                    .collect(Collectors.toMap(Items::getSku, Function.identity(), (a, b) -> a));

            List<Items> toInsert = new ArrayList<>();
            List<Items> toUpdate = new ArrayList<>();
            List<String> toDelete = new ArrayList<>(); // 可选：需要删除的 SKU

            // 比较新旧数据
            for (Items newItem : itemsList) {
                String sku = newItem.getSku();
                Items existingItem = itemCacheMap.get(sku);
                if (existingItem == null) {
                    // 新增记录
                    toInsert.add(newItem);
                } else {
                    // 比较字段是否有差异
                    if (hasDifferences(newItem, existingItem)) {
                        newItem.setItemsId(existingItem.getItemsId());
                        newItem.setAuthId(existingItem.getAuthId());
                        toUpdate.add(newItem);
                    }
                    // 从 itemCacheMap 中移除已处理的 SKU
                    itemCacheMap.remove(sku);
                }
            }

            // 剩余的 itemCacheMap 中的 SKU 是需要删除的（可选）
            //toDelete.addAll(itemCacheMap.keySet());

            // 执行批量操作
            if (!toInsert.isEmpty()) {
                itemsService.itemsInsertList(toInsert);
            }
            if (!toUpdate.isEmpty()) {
                itemsService.itemsBatchUpdate(toUpdate);
            }
            if (!toDelete.isEmpty() && shouldDelete()) { // 可选：根据需求决定是否删除
                //itemsService.batchDeleteBySkus(toDelete, authId);
            }

        }, executor);
    }
    /**
     * 获取链接信息（image_url，item_id，可能为空，需要通过createRequestTask获取）
     * @return
     */
    private static ProductItem getSearch(Items items,ShopAuth shopAuth){
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("upc",items.getUpc());
        paramMap.put("gtin",items.getGtin());
        String url = WalmartConstant.BASE_URL+WalmartConstant.GET_PRODUCTS_US_URL+WalmartConstant.GET_SEARCH_US_URL;
        String request = WalmartRequest.request(url, Method.GET, paramMap, shopAuth);
        ProductItem productItem = JSON.parseObject(request, ProductItem.class);
        return productItem;
    }
    /**
     * 创建请求报告
     * @return
     */
    @PostMapping("/createRequestTask")
    public AjaxResult createRequestTask(){
        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);
        String response = null;
        for (ShopAuth shopAuth : selectAllList) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("reportType","ITEM");
            paramMap.put("reportVersion","v1");
            //"https://marketplace.walmartapis.com/v3/reports/reportRequests";
            String url = WalmartConstant.BASE_URL+WalmartConstant.GET_REPORT_REQUEST;
            //1、把你不想要展示到报告中的字段都可以往里面写，Primary Category Path这里的值奇奇怪怪的，先不要了
            List<String> columns = Arrays.asList("Primary Category Path","Lifecycle Status", "Publish Status","Shelf Name");
            //2、添加过滤条件，这里以过滤 Publish Status = PUBLISHED为例子
            JSONObject statusFilter = new JSONObject();
            statusFilter.put("type", "enumFilter");
            statusFilter.put("columnName", "Publish Status");
            statusFilter.put("values", new String[]{"PUBLISHED"});
            //2.1、如果要过滤其他条件自行添加。比如过滤 10<=price<=1000
            JSONObject priceFilter = new JSONObject();
            priceFilter.put("type","rangeFilter");
            priceFilter.put("columnName","Price");
            priceFilter.put("from","10");
            priceFilter.put("to","1000");
            //2.2、把上面所有filter放到filters集合
            JSONArray rowsFilters = new JSONArray();
            rowsFilters.add(statusFilter);
            rowsFilters.add(priceFilter);
            //3、构建body参数，把字段和过滤条件加进来
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("excludeColumns", columns);
            //jsonBody.put("rowFilters", rowsFilters);
            response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody),shopAuth);
            JSONObject jsonObject = JSON.parseObject(response);
            String requestId = jsonObject.getString("requestId");
            System.out.println("jsonObject==========================="+jsonObject);
            redisCache.setCacheObject("itemsRequestId"+shopAuth.getAuthId(),requestId,4, TimeUnit.HOURS);
        }
        return success(response);
    }

    /** 报告请求状态 */
    @GetMapping("/requestStatusTask")
    public AjaxResult requestStatusTask(){
        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);
        if(!reportItemService.selectAll().isEmpty()){
            //reportItemService.deleteAll();
        }
        for (ShopAuth shopAuth : selectAllList) {
            Object cacheObject = redisCache.getCacheObject("itemsRequestId" + shopAuth.getAuthId());
            String requestUrl = WalmartConstant.BASE_URL+WalmartConstant.GET_REQUEST_STATUS+cacheObject;
            String request = WalmartRequest.request(requestUrl, Method.GET, null, shopAuth);
            JSONObject parseObject = JSON.parseObject(request);
            String requestStatus = parseObject.getString("requestStatus");
            if(requestStatus.equals("READY")){
                downloadReport(cacheObject,shopAuth);
            }else{
                throw new ServiceException("还未准备完成，请耐心等待！");
            }
        }
        return null;
    }

    /** 下载报告 url */
    public void downloadReport(Object cacheObject,ShopAuth shopAuth){
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestId",cacheObject);
        String url = WalmartConstant.BASE_URL+WalmartConstant.GET_DOWNLOAD_REPORT;
        String request = WalmartRequest.request(url, Method.GET, paramMap, shopAuth);
        JSONObject parseObject = JSON.parseObject(request);
        String downloadURL = parseObject.getString("downloadURL");
        String reportType = parseObject.getString("reportType");
        List<ReportItem> reportItemList = WalmartRequest.processFileFromURL(downloadURL, reportType, shopAuth,cacheObject.toString());
        reportItemService.deleteReportItem(shopAuth);
        reportItemService.insertAll(reportItemList);
        itemsService.updateItemsList(reportItemList);
    }

    /** 抓取存货数据 */
    @GetMapping("/WFS/inventory")
    public AjaxResult getInventoryTask(){

        ExecutorService executor = Executors.newFixedThreadPool(Math.min(Runtime.getRuntime().availableProcessors(), 10));

        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);

        // **链式执行，每个店铺一个一个执行**
        CompletableFuture<Void> chain = CompletableFuture.completedFuture(null);

        for (ShopAuth shopAuth : selectAllList) {
            chain = chain.thenCompose(ignore -> processInventoryShopAuth(shopAuth, executor));
        }

        // **等待所有店铺执行完成**
        chain.join();
        executor.shutdown();

        return success();

    }

    /**
     * **单个店铺的执行逻辑（独立事务）**
     */
    private CompletableFuture<Void> processInventoryShopAuth(ShopAuth shopAuth, Executor executor) {

        return CompletableFuture.runAsync(() -> {
            try {
                Inventory inventory = new Inventory();
                List<FulfillmentInventory> fulfillmentInventoryList = new ArrayList<>();

                FulfillmentInventory fulfillmentInventory = null;
                inventory.setLimit(300);
                Integer offset = 0;
                Boolean flay = true;
                while ( flay == true){
                    inventory.setOffset(offset);
                    JSONObject jsonObject = walmartUtil.listInventoryUs(inventory,shopAuth);
                    InventoryPayload inventoryPayload = JSON.parseObject(jsonObject.toString(), InventoryPayload.class);
                    if(jsonObject == null){
                        break;
                    }
                    if(inventoryPayload.getHeaders().getTotalCount() != 0) {
                        Integer nextCursor = inventoryPayload.getHeaders().getTotalCount();
                        if (nextCursor > offset) {
                            Integer newOffset = nextCursor - offset;
                            if (newOffset < inventory.getLimit()) {
                                flay = false;
                            } else if (newOffset > inventory.getLimit()) {
                                offset = offset + inventory.getLimit();
                                flay = true;
                            } else {
                                flay = false;
                                break;
                            }

                            List<InventoryPayload.InventoryItem> inventoryItems = inventoryPayload.getPayload().getInventory();
                            for (InventoryPayload.InventoryItem inventoryItem : inventoryItems) {
                                fulfillmentInventory = new FulfillmentInventory();
                                fulfillmentInventory.setInvId(IdWorker.getId());
                                fulfillmentInventory.setAuthId(shopAuth.getAuthId());
                                fulfillmentInventory.setSku(inventoryItem.getSku());
                                List<InventoryPayload.ShipNode> shipNodes = inventoryItem.getShipNodes();
                                for (InventoryPayload.ShipNode shipNode : shipNodes) {
                                    fulfillmentInventory.setModifiedDate(shipNode.getModifiedDate());
                                    fulfillmentInventory.setAvailToSellQty(shipNode.getAvailToSellQty());
                                    fulfillmentInventory.setOnHandQty(shipNode.getOnHandQty());
                                    fulfillmentInventory.setShipNodeType(shipNode.getShipNodeType());
                                }
                                fulfillmentInventoryList.add(fulfillmentInventory);
                            }
                        } else {
                            flay = false;
                        }
                    }
                }
                 fulfillmentInventoryService.deleteFulfillmentInventory(shopAuth.getAuthId());
                 fulfillmentInventoryService.fulfillmentInventoryInsertList(fulfillmentInventoryList);

            } catch (Exception e) {
                log.error("抓取存货数据失败，ShopAuth: {}", shopAuth.getAuthId(), e);
                // **失败后不影响其他店铺**
            }
        }, executor);

    }

    @GetMapping("/getInventoryLogs")
    public AjaxResult getInventoryLogs(){
        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);
        for (ShopAuth shopAuth : selectAllList) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("gtin","00782846976137");
            String url = "https://marketplace.walmartapis.com/v3/fulfillment/inventory-log";
            String request = WalmartRequest.request(url, Method.GET, paramMap, shopAuth);
            ProductItem productItem = JSON.parseObject(request, ProductItem.class);
            return success(productItem);
        }
        return null;
    }

    /** 抓取存货日志数据 */
    @GetMapping("/WFS/inventoryLogTask")
    public AjaxResult getInventoryLogTask(){

        ExecutorService executor = Executors.newFixedThreadPool(Math.min(Runtime.getRuntime().availableProcessors(), 10));

        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);

        // **链式执行，每个店铺一个一个执行**
        CompletableFuture<Void> chain = CompletableFuture.completedFuture(null);

        for (ShopAuth shopAuth : selectAllList) {
            chain = chain.thenCompose(ignore -> processInventoryLogShopAuth(shopAuth, executor));
        }

        // **等待所有店铺执行完成**
        chain.join();
        executor.shutdown();

        return success();

    }
    /**
     * **单个店铺的执行逻辑（独立事务）**
     */
    private CompletableFuture<Void> processInventoryLogShopAuth(ShopAuth shopAuth, Executor executor) {

        return CompletableFuture.runAsync(() -> {
            try {
                FulfillmentInventoryLog fulfillmentInventoryLog = null;
                List<FulfillmentInventoryLog> fulfillmentInventoryLogList = new ArrayList<>();
                List<InventoryLogSearch> inventoryLogSearches = fulfillmentInventoryLogService.getInventoryLog(shopAuth);
                for (int i = 0; i < inventoryLogSearches.size(); i++) {

                    InventoryLogSearch inventoryLogSearch = inventoryLogSearches.get(i);
                    inventoryLogSearch.setLimit(1000);
                    Integer offset = 0;
                    Boolean flay = true;
                    while (flay == true) {
                        inventoryLogSearch.setOffset(offset);
                        JSONObject jsonObject = walmartUtil.listInventoryLogUS(inventoryLogSearch, shopAuth);
                        InventoryLogPayload inventoryLogPayload = JSON.parseObject(jsonObject.toString(), InventoryLogPayload.class);
                        if (jsonObject == null) {
                            break;
                        }
                        if (inventoryLogPayload.getHeaders().getTotalCount() != 0) {
                            Integer nextCursor = inventoryLogPayload.getHeaders().getTotalCount();
                            if (nextCursor > offset) {
                                Integer newOffset = nextCursor - offset;
                                if (newOffset < inventoryLogSearch.getLimit()) {
                                    flay = false;
                                } else if (newOffset > inventoryLogSearch.getLimit()) {
                                    offset = offset + inventoryLogSearch.getLimit();
                                    flay = true;
                                } else {
                                    flay = false;
                                    break;
                                }
                                String gtin = inventoryLogPayload.getPayload().getGtin();
                                String sku = inventoryLogPayload.getPayload().getVendorSku();
                                List<InventoryLogPayload.InventoryLog> inventoryLogs = inventoryLogPayload.getPayload().getInventoryLog();
                                for (InventoryLogPayload.InventoryLog inventoryLog : inventoryLogs) {
                                    fulfillmentInventoryLog = new FulfillmentInventoryLog();
                                    fulfillmentInventoryLog.setInvlogId(IdWorker.getId());
                                    fulfillmentInventoryLog.setGtin(gtin);
                                    fulfillmentInventoryLog.setSku(sku);
                                    fulfillmentInventoryLog.setAuthId(shopAuth.getAuthId());
                                    fulfillmentInventoryLog.setFcId(inventoryLog.getFcId());
                                    fulfillmentInventoryLog.setFcName(inventoryLog.getFcName());
                                    fulfillmentInventoryLog.setChangedUnits(inventoryLog.getChangedUnits());
                                    fulfillmentInventoryLog.setTransactionTime(walmartUtil.formattedTime(inventoryLog.getTransactionTime(), "yyyy-MM-dd HH:mm:ss"));
                                    fulfillmentInventoryLog.setTransactionLocation(inventoryLog.getTransactionLocation());
                                    fulfillmentInventoryLog.setTransactionReasonCode(inventoryLog.getTransactionReasonCode());
                                    fulfillmentInventoryLog.setTransactionReasonDesc(inventoryLog.getTransactionReasonDesc());
                                    fulfillmentInventoryLog.setTransactionType(inventoryLog.getTransactionType());
                                    fulfillmentInventoryLog.setShipmentId(inventoryLog.getShipmentId());

                                    fulfillmentInventoryLogList.add(fulfillmentInventoryLog);
                                }
                            }
                        } else {
                            flay = false;
                        }
                    }
                    if(fulfillmentInventoryLogList.size()>0){
                        String gtin = inventoryLogSearch.getGtin();
                        String sku = inventoryLogSearch.getSku();
                        Date date = inventoryLogSearch.getStartDate();//年月日
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String formattedDate = null;
                        if (date != null) {
                            formattedDate = formatter.format(date);
                        }

                        // 删除现有记录
                        fulfillmentInventoryLogMapper.delete(
                                new LambdaQueryWrapper<FulfillmentInventoryLog>()
                                        .eq(FulfillmentInventoryLog::getGtin, gtin)
                                        .eq(FulfillmentInventoryLog::getAuthId, shopAuth.getAuthId())
                                        .eq(FulfillmentInventoryLog::getSku, sku)
                                        .ge(FulfillmentInventoryLog::getTransactionTime, formattedDate)
                        );

                        fulfillmentInventoryLogService.fulfillmentInventoryLogInsertList(fulfillmentInventoryLogList);
                    }
                    fulfillmentInventoryLog = null;
                    fulfillmentInventoryLogList = new ArrayList<>();

                }

            } catch (Exception e) {
                log.error("抓取存货日志数据失败，ShopAuth: {}", shopAuth.getAuthId(), e);
                // **失败后不影响其他店铺**
            }
        }, executor);

    }
    /**
     * 展示到页面上库存数据
     * @param fulfillmentInventory
     * @return
     */
    @PreAuthorize("@ss.hasPermi('walmart:inventory:list')")
    @GetMapping("/WFL/inventoryList")
    public TableDataInfo inventoryList(FulfillmentInventory fulfillmentInventory){
        startPage();
        if (fulfillmentInventory.getSkuSet() == null) {
            fulfillmentInventory.setSkuSet(new ArrayList<>()); // ✅ 防止 `skuSet` 为空
        }
        List<FulfillmentInventory> fulfillmentInventoryList = fulfillmentInventoryService.selectList(fulfillmentInventory);
        return getDataTable(fulfillmentInventoryList);
    }

    /**
     * 库存日志数据
     * @param fulfillmentInventoryLog
     * @return
     */
    @PreAuthorize("@ss.hasPermi('walmart:inventoryLog:list')")
    @GetMapping("/WFL/inventoryLogList")
    public TableDataInfo inventoryLogList(FulfillmentInventoryLog fulfillmentInventoryLog){
        startPage();
        List<FulfillmentInventoryLog> fulfillmentInventoryList = fulfillmentInventoryLogService.selectInventoryLogList(fulfillmentInventoryLog);
        return getDataTable(fulfillmentInventoryList);
    }

    /**
     * 获取所有的发货
     * @return
     */
    @GetMapping("/shipments")
    public AjaxResult getShipmentsTask(){
        ExecutorService executor = Executors.newFixedThreadPool(Math.min(Runtime.getRuntime().availableProcessors(), 10));

        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);

        // **链式执行，每个店铺一个一个执行**
        CompletableFuture<Void> chain = CompletableFuture.completedFuture(null);

        for (ShopAuth shopAuth : selectAllList) {
            chain = chain.thenCompose(ignore -> processShipmentsShopAuth(shopAuth, executor));
        }

        // **等待所有店铺执行完成**
        chain.join();
        executor.shutdown();

        return success();
    }
    /**
     * **单个店铺的执行逻辑（独立事务）**
     */
    private CompletableFuture<Void> processShipmentsShopAuth(ShopAuth shopAuth, Executor executor) {
        return CompletableFuture.runAsync(() -> {
            ShipmentCondition shipmentCondition = new ShipmentCondition();
            List<Shipment> shipmentList = new ArrayList<>();
            List<ShipmentItem> shipmentItemList = new ArrayList<>();
            LocalDateTime date  = null;
              try {
                  Map<String, Object> paramMap = null;
                  shipmentCondition.setLimit(300);
                  Integer offset = 0;
                  Boolean flay = true;
                  Long authId = shopAuth.getAuthId();

                  /** 查询是否已有货件任务*/
                  Integer result  = shipmentMapper.checkExistenceShipments(shopAuth.getAuthId());
                  if (result != null) {
                      date = shipmentMapper.delayShipmentsDate(shopAuth.getAuthId());
                      // 转换日期格式为Walmart要求的格式
                      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                      String formattedDate = date.atZone(ZoneId.of("UTC"))
                              .format(formatter);
                      shipmentCondition.setFromCreateDateN(formattedDate);

                  }

                  while ( flay == true) {
                      shipmentCondition.setOffset(offset);
                      JSONObject jsonObject = walmartUtil.listShipmentUs(shipmentCondition, shopAuth);
                      ShipmentPayload shipmentPayload = JSON.parseObject(jsonObject.toString(), ShipmentPayload.class);
                      if(jsonObject == null){
                          break;
                      }
                      if(shipmentPayload.getHeaders().getTotalCount() != 0) {
                          Integer nextCursor = shipmentPayload.getHeaders().getTotalCount();
                          if (nextCursor > offset) {
                              Integer newOffset = nextCursor - offset;
                              if (newOffset < shipmentCondition.getLimit()) {
                                  flay = false;
                              } else if (newOffset > shipmentCondition.getLimit()) {
                                  offset = offset + shipmentCondition.getLimit();
                                  flay = true;
                              } else {
                                  flay = false;
                                  break;
                              }
                              List<ShipmentPayload.Shipment> payload = shipmentPayload.getPayload();
                              for (ShipmentPayload.Shipment newShipment:payload) {
                                  Shipment shipment = new Shipment();

                                  shipmentStockMapper.update(
                                          null,
                                          new LambdaUpdateWrapper<ShipmentStock>()
                                                  .set(ShipmentStock::getActualDeliveryDate, newShipment.getActualDeliveryDate())
                                                  .eq(ShipmentStock::getShipmentId, newShipment.getShipmentId())
                                  );

                                  String uuid = IdUtils.fastSimpleUUID();
                                  BeanUtils.copyProperties(newShipment,shipment);
                                  shipment.setShiptId(uuid);
                                  shipment.setAuthId(authId);
                                  shipment.setShipFcName(newShipment.getShipToAddress().getFcName());
                                  shipment.setShipAddressLine(newShipment.getShipToAddress().getAddressLine1());
                                  shipment.setShipCity(newShipment.getShipToAddress().getCity());
                                  shipment.setShipStateCode(newShipment.getShipToAddress().getStateCode());
                                  shipment.setShipCountryCode(newShipment.getShipToAddress().getCountryCode());
                                  shipment.setShipPostalCode(newShipment.getShipToAddress().getPostalCode());
                                  shipment.setReturnAddressLine(newShipment.getReturnAddress().getAddressLine1());
                                  shipment.setReturnCity(newShipment.getReturnAddress().getCity());
                                  shipment.setReturnStateCode(newShipment.getReturnAddress().getStateCode());
                                  shipment.setReturnCountryCode(newShipment.getReturnAddress().getCountryCode());
                                  shipment.setReturnPostalCode(newShipment.getReturnAddress().getPostalCode());
                                  List<String> trackingNo = newShipment.getTrackingNo();
                                  String json = StringUtils.join(trackingNo,",");
                                  shipment.setTrackingNo(json);
                                  paramMap = new HashMap<>();
                                  paramMap.put("shipmentId",shipment.getShipmentId());
                                  paramMap.put("limit","300");
                                  paramMap.put("offset","0");
                                  String url = WalmartConstant.BASE_URL+WalmartConstant.GET_SHIPMENTS_ITEM_US_URL;
                                  String request = WalmartRequest.request(url, Method.GET, paramMap, shopAuth);
                                  ShipmentItemPayload shipmentItemPayload = JSON.parseObject(request, ShipmentItemPayload.class);
                                  List<ShipmentItemPayload.Payload> payloadList = shipmentItemPayload.getPayload();
                                  for (ShipmentItemPayload.Payload itemPayload:payloadList) {
                                      ShipmentItem shipmentItem = new ShipmentItem();
                                      String _uuid = IdUtils.fastSimpleUUID();
                                      BeanUtils.copyProperties(itemPayload,shipmentItem);
                                      shipmentItem.setShipItemId(_uuid);
                                      shipmentItem.setAuthId(authId);
                                      shipmentItemList.add(shipmentItem);
                                  }
                                  shipmentList.add(shipment);
                              }

                          } else {
                              flay = false;
                          }
                      }
                  }
                  Shipment shipment = new Shipment();
                  shipment.setAuthId(authId);
                  shipment.setCreatedDate(date);
                  // 获取数据库中的原始数据，包括时间条件
                  List<Shipment> shipmentListPlay = shipmentService.selectList(shipment);
                  List<String> existingShipmentIds = shipmentListPlay.stream()
                          .map(Shipment::getShipmentId)
                          .collect(Collectors.toList());

                  // 新旧数据的对比，删除旧数据
                  List<String> newShipmentIds = shipmentList.stream()
                          .map(Shipment::getShipmentId)
                          .collect(Collectors.toList());

                  // 计算需要删除的交集部分（存在于已有数据和新数据中的ID）
                  List<String> idsToDelete = new ArrayList<>(existingShipmentIds);
                  idsToDelete.retainAll(newShipmentIds);
                  if (!idsToDelete.isEmpty()) {
                      shipmentService.deleteShipmentsByIds(idsToDelete);
                      shipmentItemService.deleteShipmentItemsByShipmentIds(idsToDelete);
                  }

                  // 插入新数据
                  if (shipmentListPlay.isEmpty()){
                      shipmentItemService.shipmentItemInsertList(shipmentItemList);
                      shipmentService.shipmentInsertList(shipmentList);
                  }else{
                      shipmentItemService.shipmentItemInsertList(shipmentItemList);
                      shipmentService.shipmentInsertList(shipmentList);
                      //清除关联已取消的备货计划
                      clearCancelledShipmentId(authId);
                  }
              } catch (Exception e) {
                  log.error("获取发货失败，ShopAuth: {}", shopAuth.getAuthId(), e);
                  // **失败后不影响其他店铺**
              }
        }, executor);
    }
    /**
     * 添加地址
     * @param address
     * @return
     */
    @PostMapping("/shipment/addShipmentAddress")
    public AjaxResult getShipmentAddress(@RequestBody Address address){
        return success(addressService.insertAll(address));
    }

    /**
     * 修改地址
     * @param address
     * @return
     */
    @PostMapping("/shipment/updateAddress")
    public AjaxResult updateShipmentAddress(@RequestBody Address address){
        return success(addressService.updateShipmentAddress(address));
    }

    /**
     * 创建发货
     * @param inboundShipment
     * @return
     */
    @PreAuthorize("@ss.hasPermi('shipments:send:add')")
    @PostMapping("/shipment/inbound")
    public AjaxResult inboundShipments(@RequestBody InboundShipment inboundShipment){
        ShopAuth newShopAuth = new ShopAuth();
        newShopAuth.setAuthId(Long.parseLong(inboundShipment.getAuthId()));
        List<ShopAuth> selectAllList = shopAuthService.selectAllList(newShopAuth);

        List<String> allShipmentIds = new ArrayList<>();

        for (ShopAuth shopAuth : selectAllList) {
            JSONObject returnAddress = new JSONObject();
            returnAddress.put("addressLine1",inboundShipment.getAddressLine1());
            returnAddress.put("addressLine2",inboundShipment.getAddressLine2());
            returnAddress.put("city",inboundShipment.getCity());
            returnAddress.put("stateCode",inboundShipment.getStateCode());
            returnAddress.put("countryCode",shopAuth.getSite());
            returnAddress.put("postalCode",inboundShipment.getZipCode());
            JSONObject inboundServices = new JSONObject();
            inboundServices.put("inventoryTransferService","Y");
            List<OrderItems> orderItemsList = inboundShipment.getOrderItemsList();
            JSONArray orderItems = new JSONArray();
            JSONObject item = null;
            for (OrderItems order:orderItemsList) {
                item = new JSONObject();
                item.put("productId",order.getGtin());
                item.put("productType","GTIN");
                item.put("sku",order.getSku());
                item.put("itemDesc",order.getProductName());
                item.put("itemQty",order.getTotalUnits());
                long vendorPackQty = Math.round(order.getTotalUnits() / order.getMasterCase());
                item.put("vendorPackQty",vendorPackQty);
                item.put("innerPackQty",order.getMasterCase());
                String expectedDeliveryDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(order.getExpectedDeliveryDate());
                item.put("expectedDeliveryDate",expectedDeliveryDate);
                orderItems.add(item);
            }
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("inboundOrderId",inboundShipment.getInboundOrderId());
            jsonBody.put("inboundServices",inboundServices);
            jsonBody.put("returnAddress",returnAddress);
            jsonBody.put("orderItems",orderItems);
            String url = WalmartConstant.BASE_URL+WalmartConstant.GET_SHIPMENTS_US_URL;
            Map<String, Object> paramMap = new HashMap<>();
            String requestPost = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
            JSONObject jsonObject = JSON.parseObject(requestPost);
            // 从 jsonObject 中获取 payload 数组
            JSONArray payloadArray = jsonObject.getJSONArray("payload");

            for (int i = 0; i < payloadArray.size(); i++) {
                // 获取每个 payload 元素
                JSONObject currentPayload = payloadArray.getJSONObject(i);
                // 获取每个 payload 元素中的 shipmentId
                String shipmentId = currentPayload.getString("shipmentId");
                allShipmentIds.add(shipmentId);
                //通过shipmentId获取发货信息
                shipmentItemService.getShipmentItemByShipmentId(shipmentId,shopAuth,inboundShipment);
                //设置walmart备货计划关联ID
                iWalmartStockPlanService.setWalmartStockPlanShipmentId(shipmentId, inboundShipment.getStockId());
            }
        }
        return AjaxResult.success(allShipmentIds);
    }

    /**
     * 更新货运数量
     * @param shipmentItem
     * @return
     */
    @PostMapping("/shipment/updatedShipmentQty")
    public AjaxResult updatedShipmentQty(@RequestBody ShipmentItem shipmentItem){

            Shipment shipment = new Shipment();
            String shipmentId = shipmentItem.getShipmentId();
            String InboundOrderId = shipmentItem.getInboundOrderId();
            shipment.setShipmentId(shipmentId);
            shipment.setInboundOrderId(InboundOrderId);
            shipment  = shipmentService.selectShipment(shipment);
            if(null  == shipment){
                throw new ServiceException("获取运件信息失败。");
            }
            ShopAuth shopAuth  = shopAuthService.selectByAuthId(shipment.getAuthId());

            JSONArray orderItems = new JSONArray();
            JSONObject item =  new JSONObject();
            item.put("sku",shipmentItem.getSku());
            item.put("updatedShipmentQty",shipmentItem.getItemQty());
            orderItems.add(item);
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("inboundOrderId",InboundOrderId);
            jsonBody.put("shipmentId",shipmentId);
            jsonBody.put("orderItems",orderItems);
            String url = WalmartConstant.BASE_URL+WalmartConstant.GET_SHIPMENTS_QTY;
            String requestPost = WalmartRequest.requestPut(url, jsonBody, JSONUtil.toJsonStr(jsonBody), shopAuth);
            JSONObject jsonObject = JSON.parseObject(requestPost);
            String requestStatus = jsonObject.getString("status");
            if(requestStatus.equals("OK")){
                //更新货运数量
                shipmentItemService.updatedShipmentQty(shipmentItem);
            }else{
                // 获取错误信息
                JSONArray errors = jsonObject.getJSONArray("errors");
                if (errors != null && !errors.isEmpty()) {
                    // 提取第一个错误信息
                    JSONObject error = errors.getJSONObject(0);
                    String code = error.getString("code");
                    String field = error.getString("field");
                    String description = error.getString("description");
                    String info = error.getString("info");
                    String severity = error.getString("severity");
                    String category = error.getString("category");

                    // 根据需要处理错误信息
                    String errorMessage = String.format("Error Code: %s, Field: %s, Description: %s, Info: %s, Severity: %s, Category: %s",
                            code, field, description, info, severity, category);

                    // 抛出自定义异常或记录日志
                    throw new ServiceException("更新货运数量失败，" + errorMessage);
                } else {
                    // 如果没有错误信息
                    throw new ServiceException("更新货运数量失败，未知错误");
                }
            }
            return null;
    }

    /**
     * 创建入库货件标签
     * @param shipmentLabel
     * @return
     */
    @PreAuthorize("@ss.hasPermi('walmart:shipment:set')")
    @PostMapping("/shipment/createShipmentLabel")
    public AjaxResult createShipmentLabel(@RequestBody ShipmentLabel shipmentLabel){

        String shipmentId = shipmentLabel.getShipmentId();
        String labelSize = shipmentLabel.getLabelSize();
        String labelFormat = shipmentLabel.getLabelFormat();
        Integer pallets = shipmentLabel.getPallet();
        Integer singleSku =  shipmentLabel.getSingleSku();
        Integer mixedSkus =  shipmentLabel.getMixedSkus();

        ShopAuth shopAuth  = shopAuthService.selectByAuthId(shipmentLabel.getShopAuthId());

        // 组装 loadTypes 数组
        JSONArray loadTypes = new JSONArray();
        // 处理 Pallet 类型
        if (pallets != null) {
            JSONObject loadTypePallet = new JSONObject();
            loadTypePallet.put("count", pallets);
            loadTypePallet.put("loadType", "PALLET");
            loadTypes.add(loadTypePallet);
        }
        // 处理 Single SKU 类型
        if (singleSku != null && singleSku > 0) {
            JSONObject loadTypeSingleSku = new JSONObject();
            loadTypeSingleSku.put("count", singleSku);
            loadTypeSingleSku.put("loadType", "SINGLE SKU");
            loadTypes.add(loadTypeSingleSku);
        }
        // 处理 Mixed SKUs 类型
        if (mixedSkus != null && mixedSkus > 0) {
            JSONObject loadTypeMixedSkus = new JSONObject();
            loadTypeMixedSkus.put("count", mixedSkus);
            loadTypeMixedSkus.put("loadType", "MIXED SKUS");
            loadTypes.add(loadTypeMixedSkus);
        }

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("shipmentId",shipmentId);
        jsonBody.put("labelSize",labelSize);
        jsonBody.put("labelFormat",labelFormat);
        jsonBody.put("loadTypes",loadTypes);

        String url = WalmartConstant.BASE_URL+WalmartConstant.GET_SHIPMENTS_LABEL;
        // 调用示例
        byte[] pdfData = WalmartRequest.requestPostShipmentLabel(url, jsonBody, JSONUtil.toJsonStr(jsonBody), shopAuth);

        //保存入库件pdf
        shipmentLabelService.saveShipmentLabelPdf(pdfData, shipmentLabel );

        return AjaxResult.success();  // 返回成功响应
    }

    /**
     * 下载打印标签
     * @param shipmentId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('walmart:shipment:labelPrint')")
    @GetMapping("/shipment/downloadLabel")
    public ResponseEntity<Resource> downloadLabel(@RequestParam String shipmentId) {
        try {
            QueryWrapper<ShipmentLabel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("shipment_id", shipmentId); // 根据 shipmentId 字段查询

            ShipmentLabel shipmentLabel = shipmentLabelMapper.selectOne(queryWrapper);
            if(shipmentLabel == null){
                throw new ServiceException("PDF文件不存在，请核查。");
            }
            String shipmentLabelPath = shipmentLabel.getShipmentLabelPath();
            String localPath = RuoYiConfig.getProfile();
            // 拼接完整的文件路径
            Path filePath = Paths.get(localPath,shipmentLabelPath);  // 假设返回的是相对路径
            // 确保文件存在
            File file = filePath.toFile();
            if (!file.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
            if (filePath.getFileName().toString().contains("..")) {
                throw new InvalidPathException("", "检测到非法路径字符");
            }

            // 读取文件内容
            byte[] fileContent = Files.readAllBytes(filePath);  // 使用 Files.readAllBytes 读取文件内容
            // 创建 ByteArrayResource 返回文件内容
            ByteArrayResource resource = new ByteArrayResource(fileContent);

            // 3. 设置响应头（含中文文件名处理）
            // 获取文件名，如果为空则设置默认文件名
            String fileName = resource.getFilename() != null ? resource.getFilename() : "default_label.pdf";

            // 设置响应头（包含中文文件名处理）
            String encodedFileName = URLEncoder.encode(fileName, String.valueOf(StandardCharsets.UTF_8));

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE)
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename*=UTF-8''" + encodedFileName)
                    .contentLength(resource.contentLength())
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
    /**
     * 更新货件追踪
     * @param shipmentTracking
     * @return
     */
    @PreAuthorize("@ss.hasPermi('walmart:shipmentTrack:set')")
    @PostMapping("/shipment/setShipmentTracking")
    public AjaxResult setShipmentTracking(@RequestBody ShipmentTracking shipmentTracking) {

        List<String> trackingNumbers = shipmentTracking.getTrackingNumbers();
        String shipmentId = shipmentTracking.getShipmentId();
        String carrierName = shipmentTracking.getCarrierName();
        Long authId = shipmentTracking.getAuthId();

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("shipmentId",shipmentId);
        jsonBody.put("carrierName",carrierName);
        jsonBody.put("trackingInfo",trackingNumbers);

        ShopAuth shopAuth = shopAuthService.selectByAuthId(authId);
        String url = WalmartConstant.BASE_URL+WalmartConstant.GET_SHIPMENTS_TRACKING;

        String requestPost = WalmartRequest.requestPost(url, jsonBody, JSONUtil.toJsonStr(jsonBody), shopAuth);
        JSONObject jsonObject = JSON.parseObject(requestPost);
        String requestStatus = jsonObject.getString("status");
        if(requestStatus.equals("OK")){
            //通过shipmentId获取发货信息
            shipmentItemService.getShipmentItemByShipmentId(shipmentId,shopAuth,null);
        }else{
            // 获取错误信息
            JSONArray errors = jsonObject.getJSONArray("errors");
             throw new ServiceException("更新货运追踪失败，" + errors);
        }
        return null;
    }
    /**
     * 货件明细
     * @param shipmentItem
     * @return
     */
    @GetMapping("/shipment/getShipmentItem")
    public TableDataInfo getShipmentItem(ShipmentItemDTO shipmentItem){
        List<ShipmentItemDTO> shipmentItemList = shipmentItemService.getShipmentItemDTO(shipmentItem);
        return getDataTable(shipmentItemList);
    }

    /**
     * 取消发货，修改状态
     * @param shipment
     * @return
     */
    @PreAuthorize("@ss.hasPermi('walmart:shipment:cancelled ')")
    @DeleteMapping("/shipment/cancelShipment")
    public AjaxResult cancelShipment(Shipment shipment){
        Long authId = shipment.getAuthId();
        ShopAuth shopAuth = shopAuthService.selectByAuthId(authId);

        String url = WalmartConstant.BASE_URL+WalmartConstant.GET_SHIPMENTS_US_URL+"/"+shipment.getInboundOrderId();
        String request = WalmartRequest.request(url, Method.DELETE, null, shopAuth);
        JSONObject parseObject = JSON.parseObject(request);
        if(parseObject.getString("status").equals("OK")){
            //修改货件发货数0，状态。
            shipmentService.updateStatus(shipment);
            //修改货件明细发货数0
            shipmentItemService.updateShipmentItemQty(shipment.getShipmentId());
            //取消关联的备货计划
            iWalmartStockPlanService.updateWalmartStockPlanShipmentId(shipment.getShipmentId());
            //取消新版备货计划
            iWalmartStockPlanService.cancelShipmentStock(shipment.getShipmentId());

        }
        return success(request);
    }



    /**
     * 查询产品配对的walmart链接详细
     */
    @PreAuthorize("@ss.hasPermi('commodity:products:walmartView')")
    @GetMapping(value = "/pairView")
    public AjaxResult getPairView(  @RequestParam(value = "startTime", required = false) Date startTime,
                                    @RequestParam(value = "endTime", required = false) Date endTime,
                                    @RequestParam(value = "id", required = false) Long id)
    {
        return success(pairProductsService.selectPairView(id,startTime,endTime));
    }


    /**
     * 查询所有店铺未配对的产品记录有多少条
     * @return
     */
    @GetMapping(value = "/items/getUnpairedProductsStats")
    public AjaxResult getUnpairedProductsStats()
    {
        return success(pairProductsService.selectUnpairedProductsStats());
    }

    /**
     * 清除已取消的备货计划
     * @return
     */
    public void clearCancelledShipmentId(Long authId) {
        //查询指定 authId 下所有非空的 shipment_id（去重）
        List<String> shipmentIds  = iWalmartStockPlanService.selectDistinctShipmentIdsByAuthId(authId);
        if (CollectionUtils.isEmpty(shipmentIds)) return;

        //查询已取消状态的 shipment_id 列表
        List<String> cancelledIds = shipmentService.selectCancelledShipmentIds(shipmentIds);
        if (!CollectionUtils.isEmpty(cancelledIds)) {
            //已取消的walmart入库单，清空备货计划的shipment_id
            iWalmartStockPlanService.clearShipmentIdBatch(cancelledIds);
        }
    }

    /**
     * 获取所有的入库记录
     * @return
     */
    @GetMapping("/shipments/Inbound")
    public AjaxResult getInventoryInboundTask(){
        ExecutorService executor = Executors.newFixedThreadPool(Math.min(Runtime.getRuntime().availableProcessors(), 10));

        List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);

        // **链式执行，每个店铺一个一个执行**
        CompletableFuture<Void> chain = CompletableFuture.completedFuture(null);

        for (ShopAuth shopAuth : selectAllList) {
            chain = chain.thenCompose(ignore -> processInventoryInboundShopAuth(shopAuth, executor));
        }

        // **等待所有店铺执行完成**
        chain.join();
        executor.shutdown();

        return success();
    }

    /**
     * 获取所有的（入库）记录
     * **单个店铺的执行逻辑（独立事务）**
     */
    private CompletableFuture<Void> processInventoryInboundShopAuth(ShopAuth shopAuth, Executor executor) {

        return CompletableFuture.runAsync(() -> {
            try {
                ShipmentInbound shipmentInbound = null;
                List<ShipmentInbound> shipmentInboundList = new ArrayList<>();

                List<InventoryLogSearch> inventoryLogSearches = fulfillmentInventoryLogService.getInventoryInboundLog(shopAuth);
                for (int i = 0; i < inventoryLogSearches.size(); i++) {

                    InventoryLogSearch inventoryLogSearch = inventoryLogSearches.get(i);
                    inventoryLogSearch.setLimit(300);
                    inventoryLogSearch.setTransactionType("Receipt");//只查询入库的数据
                    inventoryLogSearch.setTransactionLocation("Inventory");
                    Integer offset = 0;
                    Boolean flay = true;
                    while (flay == true) {
                        inventoryLogSearch.setOffset(offset);
                        JSONObject jsonObject = walmartUtil.listInventoryLogUS(inventoryLogSearch, shopAuth);
                        InventoryLogPayload inventoryLogPayload = JSON.parseObject(jsonObject.toString(), InventoryLogPayload.class);
                        if (jsonObject == null) {
                            break;
                        }
                        if (inventoryLogPayload.getHeaders().getTotalCount() != 0) {
                            Integer nextCursor = inventoryLogPayload.getHeaders().getTotalCount();
                            if (nextCursor > offset) {
                                Integer newOffset = nextCursor - offset;
                                if (newOffset < inventoryLogSearch.getLimit()) {
                                    flay = false;
                                } else if (newOffset > inventoryLogSearch.getLimit()) {
                                    offset = offset + inventoryLogSearch.getLimit();
                                    flay = true;
                                } else {
                                    flay = false;
                                    break;
                                }
                                String gtin = inventoryLogPayload.getPayload().getGtin();
                                String sku = inventoryLogPayload.getPayload().getVendorSku();
                                List<InventoryLogPayload.InventoryLog> inventoryLogs = inventoryLogPayload.getPayload().getInventoryLog();
                                for (InventoryLogPayload.InventoryLog inventoryLog : inventoryLogs) {
                                    shipmentInbound = new ShipmentInbound();
                                    shipmentInbound.setId(IdWorker.getId());
                                    shipmentInbound.setGtin(gtin);
                                    shipmentInbound.setSku(sku);
                                    shipmentInbound.setShipmentId(inventoryLog.getShipmentId());
                                    shipmentInbound.setInboundQuantity(inventoryLog.getChangedUnits().intValue());
                                    shipmentInbound.setInboundTime(walmartUtil.formattedTime(inventoryLog.getTransactionTime(), "yyyy-MM-dd HH:mm:ss"));
                                    shipmentInbound.setAuthId(shopAuth.getAuthId());
                                    shipmentInboundList.add(shipmentInbound);
                                }
                            }
                        } else {
                            flay = false;
                        }
                    }
                    //插入数据
                    if(shipmentInboundList.size()>0){
                        String gtin = inventoryLogSearch.getGtin();
                        String sku = inventoryLogSearch.getSku();
                        Date date = inventoryLogSearch.getStartDate();//年月日
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String formattedDate = null;
                        if (date != null) {
                            formattedDate = formatter.format(date);
                        }

                        // 查询现有 ShipmentInbound 记录以获取 unverifiedQuantity
                        List<ShipmentInbound> existingRecords = shipmentInboundMapper.selectList(
                                new LambdaQueryWrapper<ShipmentInbound>()
                                        .eq(ShipmentInbound::getGtin, gtin)
                                        .eq(ShipmentInbound::getSku, sku)
                                        .ge(formattedDate != null, ShipmentInbound::getInboundTime, formattedDate)
                        );

                        // 创建一个 Map 存储 unverifiedQuantity，按 shipment_id、sku、gtin 组合
                        Map<String, Integer> unverifiedQuantityMap = new HashMap<>();
                        for (ShipmentInbound record : existingRecords) {
                            String key = record.getShipmentId() + "|" + record.getSku() + "|" + record.getGtin()+ "|" + record.getInboundTime();
                            unverifiedQuantityMap.put(key, record.getUnverifiedQuantity());
                        }

                        // 删除现有记录
                        shipmentInboundMapper.delete(
                                new LambdaQueryWrapper<ShipmentInbound>()
                                        .eq(ShipmentInbound::getGtin, gtin)
                                        .eq(ShipmentInbound::getSku, sku)
                                        .eq(ShipmentInbound::getAuthId, shopAuth.getAuthId())
                                        .ge(ShipmentInbound::getInboundTime, formattedDate)
                        );

                        // 在插入前为 shipmentInboundList 设置 unverifiedQuantity
                        for (ShipmentInbound newRecord : shipmentInboundList) {
                            String key = newRecord.getShipmentId() + "|" + newRecord.getSku() + "|" + newRecord.getGtin() + "|" + newRecord.getInboundTime();
                            if (unverifiedQuantityMap.containsKey(key)) {
                                newRecord.setUnverifiedQuantity(unverifiedQuantityMap.get(key));
                            } else {
                                // 如果没有匹配的记录，设置默认值
                                newRecord.setUnverifiedQuantity(newRecord.getInboundQuantity()); // 或其他默认值
                            }
                        }

                        // 步骤 5：插入更新后的 shipmentInboundList
                        shipmentInboundService.shipmentInboundInsertList(shipmentInboundList);
                    }
                    shipmentInbound = null;
                    shipmentInboundList = new ArrayList<>();

                }

            } catch (Exception e) {
                log.error("抓取存货日志数据失败，ShopAuth: {}", shopAuth.getAuthId(), e);
                // **失败后不影响其他店铺**
            }
        }, executor);
    }

    /**
     * 手动绑定备货计划
     * @param ShipmentStockFilters
     * @return
     */
    @PostMapping("/shipment/bingShipmentStock")
    public AjaxResult bingShipmentStock(@RequestBody ShipmentStockFilters ShipmentStockFilters) {

        if(ShipmentStockFilters.getStockId().equals("")){
            throw new ServiceException("获取备货计划ID失败" );
        }
        if(ShipmentStockFilters.getShipmentId().equals("")){
            throw new ServiceException("获取ShipmentId失败");
        }
        shipmentStockService.bingShipmentStock(ShipmentStockFilters);
        return null;
    }

    // 判断两个 Items 是否有差异
    private boolean hasDifferences(Items newItem, Items existingItem) {
        // 比较关键字段，忽略 itemsId（因为它是 UUID，每次生成不同）
        return !Objects.equals(newItem.getProductName(), existingItem.getProductName()) ||
                !Objects.equals(newItem.getLifecycleStatus(), existingItem.getLifecycleStatus()) ||
                !Objects.equals(newItem.getMart(), existingItem.getMart()) ||
                !Objects.equals(newItem.getAmount(), existingItem.getAmount()) ||
                !Objects.equals(newItem.getCurrency(), existingItem.getCurrency()) ||
                !Objects.equals(newItem.getPublishedStatus(), existingItem.getPublishedStatus()) ||
                !Objects.equals(newItem.getProductType(), existingItem.getProductType()) ||
                !Objects.equals(newItem.getShelf(), existingItem.getShelf()) ||
                !Objects.equals(newItem.getUpc(), existingItem.getUpc()) ||
                !Objects.equals(newItem.getWpid(), existingItem.getWpid()) ||
                !Objects.equals(newItem.getImageUrl(), existingItem.getImageUrl()) ||
                //!Objects.equals(newItem.getItemId(), existingItem.getItemId()) ||
                !Objects.equals(newItem.getCustomerRating(), existingItem.getCustomerRating()) ||
                !Objects.equals(newItem.getNumReviews(), existingItem.getNumReviews()) ||
                !Objects.equals(newItem.getAvailToSellQty(), existingItem.getAvailToSellQty());
    }

    // 是否执行删除逻辑（可根据配置或需求决定）
    private boolean shouldDelete() {
        // 可通过配置文件或参数控制是否删除
        return false; // 你的需求中提到不执行删除
    }
}
